<template>
  <div class="box">
    <div :style="{ top: `${data.translateY}px` }" @touchstart="touchstartFun" @touchmove="touchmoveFun"
      @touchend="touchendFun" @scroll="scrollEvent" class="scroll-box">
      <div v-if="data.startTextShow" class="loadingBox">{{ data.startText }}</div>
      <slot />
      <div v-if="!isScroll" class="end-text">{{ endText }}</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs } from "vue";

const $props = defineProps({
  endText: {
    type: String,
    default: "没有更多了",
  },
  isScroll: Boolean,
});

const $emits = defineEmits(["getList", "refreshFun"]);
const data = reactive({
  scrollEl: null,
  startText: "释放即可刷新",
  startTextShow: false,
  scrollTop: 0, //滚动条卷起的长度
  startY: 0, //手指按下开始的位置
  translateY: 0, //拖动的位置
});

//手指按下
const touchstartFun = (e: any) => {
  //获取手指按下开始的位置
  data.startY = e.targetTouches[0].pageY;
};

//手指移动的过程
const touchmoveFun = (e: any) => {
  let y = e.targetTouches[0].pageY;
  console.log(y > data.startY, y, data.startY);
  if (y > data.startY) {
    data.startTextShow = true;
    let translateY = (y - data.startY) / 2;
    data.translateY = translateY > 150 ? 150 : translateY;
  } else {
    data.startTextShow = false;
    data.translateY = 0;
  }
};

// //手指抬起
const touchendFun = (e: any) => {
  let y = e.changedTouches[0].pageY;
  if (y > data.startY) {
    data.translateY = 0;
    data.startText = "加载中...";
    $emits("refreshFun", () => {
      data.startTextShow = false;
      data.startText = "释放即可刷新";
    });
  }
};

const scrollEvent = (e: any) => {
  data.scrollTop = e.srcElement.scrollTop;
  if (!$props.isScroll) return;
  //当滚动条快要触底的时候
  if (data.scrollTop + e.srcElement.offsetHeight > e.srcElement.scrollHeight - 150) {
    $emits("getList");
  }
};
</script>

<style scoped>
.box {
  overflow: hidden;
  position: relative;
  width: 100%;
  height: 90vh;
}

.box .loadingBox {
  padding: 20px;
  text-align: center;
}

.scroll-box {
  height: 90vh;
  width: 100%;
  overflow: auto;
  transition: all 0s ease 0s;
  position: absolute;
  right: 0;
}

.scroll-box .end-text {
  text-align: center;
  height: 50px;
  line-height: 50px;
  color: #999;
}
</style>